package com.ygqh.baby.handler;

import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.ProductStatus;
import com.ygqh.baby.model.GroupOrderCommitParam;
import com.ygqh.baby.model.SaveMainOrderParam;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.po.YgCouponDetail;
import com.ygqh.baby.po.YgGroupBuying;
import com.ygqh.baby.po.YgUserAddress;
import com.ygqh.baby.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 〈〉
 *
 * @author guohao
 * @date 2018/12/28 16:39
 * @since 1.0.0
 */
@Component
public class GroupBuyOrderCommitHandler extends BaseCommitOrderHandler {

    @Autowired
    private YgShoppingCarService ygShoppingCarService;
    @Autowired
    private YgUserAddressService ygUserAddressService;

    @Autowired
    private YgOrderService ygOrderService;

    @Autowired
    private YgCouponDetailService ygCouponDetailService;
    @Autowired
    private YgGroupBuyingService ygGroupBuyingService;

    @Autowired
    private SaveMainOrderHandler saveMainOrderHandler;

    public Message commitOrder(GroupOrderCommitParam commitParam) {
        List<YgShoppingCarModel> carList = ygShoppingCarService.findItemInfoPt(commitParam.getSkuList(), commitParam.getUserId(), commitParam.getDistribution(), commitParam.getSalesPlatform());

        Message addressMsg = ygUserAddressService.validateUserAddress(commitParam.getUserId(), commitParam.getUserAddressId(),
                commitParam.getIdentityNo(), carList, commitParam.getOrderType());
        if (!Message.isSuccess(addressMsg)) {
            return addressMsg;
        }
        Map<String, Object> addressExtra = (Map<String, Object>) addressMsg.getExtra();
        YgUserAddress address = (YgUserAddress) addressExtra.get("address");
        // 是否为保税仓订单
        Boolean trustoneOrderFlag = (Boolean) addressExtra.get("trustoneOrderFlag");


        Message checkProduct = checkProduct(carList);
        if (!checkProduct.getType().equals(Message.Type.success)) {
            return checkProduct;
        }

        Message checkStock = checkStock(carList);
        if (!checkStock.getType().equals(Message.Type.success)) {
            return checkStock;
        }

        Message jiaJiaGouMsg = this.validateJiaJiaGou(carList,commitParam.getSalesPlatform());
        if (!jiaJiaGouMsg.getType().equals(Message.Type.success)) {
            return jiaJiaGouMsg;
        }
        Message validateManZeng = this.validateManZeng(carList,commitParam.getSalesPlatform());
        if (!validateManZeng.getType().equals(Message.Type.success)) {
            return validateManZeng;
        }

        BigDecimal productPrice = BigDecimal.ZERO;
        BigDecimal specialPrice = BigDecimal.ZERO;
        BigDecimal ptPrice = BigDecimal.ZERO;

        for (YgShoppingCarModel carModel : carList) {
            productPrice = productPrice.add(carModel.getSalesPrice().multiply(new BigDecimal(carModel.getQuantity())));
            ptPrice = ptPrice.add(carModel.getRealSalesPrice().multiply(new BigDecimal(carModel.getQuantity())));
            if (carModel.getIsSpecial()) {
                specialPrice = specialPrice.add(carModel.getSalesPrice().multiply(new BigDecimal(carModel.getQuantity())));
            }
        }
        specialPrice = ptPrice;
        // 校验促销是否满足条件

        /**
         * 1、 优惠优先级按 满减、特例品，优惠券、运费顺序来。
         * 如：现有活动为满100-5，满199包邮，且用户有满200-50的优惠券，这时如果用户的初始订单金额为250，
         * 最后用户需要支付的金额计算过程为： 250-5=245>200(满足优惠券使用条件)
         * 245-50=195<199（不满足包邮条件，需加收运费） 195+10=205（用户最后需要支付的金额）
         */
        // 拼团订单总金额金额
        Map<String, Object> manJian = ygOrderService.getManJianPrice(ptPrice, commitParam.getFormId(), commitParam.getUserId());
        Boolean useCoupon = (Boolean) manJian.get("useCoupon");

        BigDecimal manJianPrice = (BigDecimal) manJian.get("manjianPrice");
        BigDecimal couponPrice = BigDecimal.ZERO;
        YgCouponDetail couponDetail = null;
        if (useCoupon) {
            BigDecimal couponValidPrice = ptPrice.subtract(manJianPrice).subtract(specialPrice);
            Boolean onlySpecial = false;
            if (couponValidPrice.compareTo(BigDecimal.ZERO) > 0) {
                onlySpecial = true;
            }

            if (commitParam.getCouponDetailId() != null) {
                couponDetail = ygCouponDetailService.findById(commitParam.getCouponDetailId(), commitParam.getUserId());

            }
            Message couponMsg = ygOrderService.validateCoupon(couponDetail, couponValidPrice, onlySpecial, carList, commitParam.getSalesPlatform());
            if (!couponMsg.getType().equals(Message.Type.success)) {
                return couponMsg;
            }
            couponPrice = (BigDecimal) couponMsg.getExtra();
        }

        // 当商品金额-新客及自选包优惠金额 - 满减金额 -优惠券金额 < 0
        BigDecimal price4exp = ptPrice.subtract(manJianPrice).subtract(couponPrice);
        if (price4exp.compareTo(BigDecimal.ZERO) < 0) {
            price4exp = new BigDecimal("0");
        }

        // BigDecimal expPrice = this.getExpressPrice(price4exp);// 运费
        // 运费 拼团订单包邮
        BigDecimal expPrice = new BigDecimal(0);
        // 订单总金额 （最终支付金额） = 商品总额(含加价购金额) -优惠卷金额 - 满减金额+ 运费
        BigDecimal orderPrice = price4exp.add(expPrice);
        if (orderPrice.compareTo(commitParam.getTotalPrice()) != 0) {
            return Message.error("订单金额有误。", orderPrice);
        }

        Message checkAccountPrice = checkAccountPrice(commitParam.getAccountPrice(), orderPrice, commitParam.getUserId());
        if (!checkAccountPrice.getType().equals(Message.Type.success)) {
            return checkAccountPrice;
        }
        // 开团
        Long groupBuyId = commitParam.getGroupBuyId();
        if (groupBuyId == null || groupBuyId.intValue() == 0) {
            // 完成数量统一在支付回调中处理
            YgGroupBuying groupBuying = ygGroupBuyingService.addGroupBuyIng(commitParam.getGroupId(), commitParam.getUserId(), 0L);
            groupBuyId = groupBuying.getId();
        }

        SaveMainOrderParam saveMainOrderParam = buildSaveMainOrderParam(commitParam, manJianPrice, couponPrice, expPrice);
        saveMainOrderParam.setReleationId(groupBuyId);
        return saveMainOrderHandler.saveMainOrder(saveMainOrderParam);
    }

    private SaveMainOrderParam buildSaveMainOrderParam(GroupOrderCommitParam commitParam, BigDecimal manjianPrice, BigDecimal couponPrice, BigDecimal expressPrice) {
        SaveMainOrderParam saveMainOrderParam = new SaveMainOrderParam();
        saveMainOrderParam.setUserId(commitParam.getUserId());
        saveMainOrderParam.setUserName(commitParam.getUserName());
        saveMainOrderParam.setAddressId(commitParam.getUserAddressId());
        saveMainOrderParam.setCouponDetailId(commitParam.getCouponDetailId());
        saveMainOrderParam.setTotalPrice(commitParam.getTotalPrice().subtract(commitParam.getAccountPrice()));
        saveMainOrderParam.setAccountPrice(commitParam.getAccountPrice());
        saveMainOrderParam.setIdentityNo(commitParam.getIdentityNo());
        saveMainOrderParam.setSalesPlatform(commitParam.getSalesPlatform());
        saveMainOrderParam.setAppType(commitParam.getAppType());
        saveMainOrderParam.setPayType(commitParam.getPayType());
        saveMainOrderParam.setFormId(commitParam.getFormId());
        saveMainOrderParam.setUserRemark(commitParam.getUserRemark());
        saveMainOrderParam.setOrderType(commitParam.getOrderType());
        saveMainOrderParam.setPlatformNo(commitParam.getPlatformNo());

        saveMainOrderParam.setSkuList(commitParam.getSkuList());
        saveMainOrderParam.setSourceCode(commitParam.getSourceCode());
        saveMainOrderParam.setReleationId(commitParam.getGroupBuyId());
        saveMainOrderParam.setManjinPrice(manjianPrice);
        saveMainOrderParam.setYhqPrice(couponPrice);
        saveMainOrderParam.setExpressPrice(expressPrice);
        return saveMainOrderParam;
    }

    @Override
    public Message checkProduct(List<YgShoppingCarModel> carList) {
        for (YgShoppingCarModel car : carList) {
            if (ProductStatus.InStock.equals(car.getSaleStatus()) || DataStatus.Delete.equals(car.getSkuStatus())) {
                return Message.error("亲，你购买商品已下架。", car.getProductName());
            }
            if (car.getPromotionPrice() == null || car.getPromotionPrice().compareTo(BigDecimal.ZERO) <= 0) {
                return Message.error("亲，" + car.getProductName() + " 拼团活动已结束。", car.getProductName());
            }
        }
        return Message.success(null);
    }
}
